package com.library.admin.listener;

import books.borrowing.entity.SubscriberEntity;
import books.borrowing.util.EUserProfile;

import com.library.admin.AdmLibrary;
import com.library.admin.Menu;
import com.library.admin.form.LoginForm;
import com.library.admin.service.LibraryService;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Window.Notification;

public class LoginSubmitListener implements ClickListener {
	private static final long serialVersionUID = -6649097614811119780L;

	private LoginForm loginForm;

	public LoginSubmitListener(LoginForm loginForm) {
		this.loginForm = loginForm;
	}

	public void buttonClick(ClickEvent event) {
		AdmLibrary libraryApplication = (AdmLibrary) event.getComponent().getApplication();
		
		if (loginForm.isValid()) {
			String login = loginForm.getLoginTextField().getValue().toString();
			String password = loginForm.getPasswordTextField().getValue().toString();

			try {
				SubscriberEntity connectedUser = LibraryService.getServiceSubscriber().connect(login, password);

				libraryApplication.setConnectedUser(connectedUser);
				Menu menu = (Menu) loginForm.getParent();
				menu.removeComponent(loginForm);
				
				if (connectedUser.getProfile().equals(EUserProfile.SUPER_ADMIN)) {
					menu.setSuperAdminMode();
				}
				else if (connectedUser.getProfile().equals(EUserProfile.BOOK_ADMIN)) {
					menu.setBookAdminMode();
				}
				else if (connectedUser.getProfile().equals(EUserProfile.SUBRENT_ADMIN)) {
					menu.setSubRentAdminMode();
				}
				else {
					libraryApplication.setConnectedUser(null);
					libraryApplication.getMainWindow().showNotification(
							"Vous ne disposez pas de droits d'administrateur",
							Notification.TYPE_WARNING_MESSAGE);
				}
			}
			catch (Exception e) {
				libraryApplication.getMainWindow().showNotification(
						"Login ou mot de passe incorrect",
						Notification.TYPE_ERROR_MESSAGE);
				e.printStackTrace();
			}
		}
		else {
			libraryApplication.getMainWindow().showNotification(
					"Veuillez remplir tous les champs",
					Notification.TYPE_WARNING_MESSAGE);					
		}
	}
}
